package com.sky.service.impl;

import com.alibaba.fastjson.JSON;
import com.sky.dto.UserLoginDTO;
import com.sky.entity.User;
import com.sky.mapper.UserMapper;
import com.sky.properties.WeChatProperties;
import com.sky.result.Result;
import com.sky.service.UserService;
import com.sky.utils.HttpClientUtil;
import com.sky.utils.JwtUtil;
import com.sky.vo.UserLoginVO;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import java.time.LocalDateTime;
import java.util.HashMap;
import java.util.Map;

@Service
@Slf4j
public class UserServiceImpl implements UserService {
    @Autowired
    private WeChatProperties weChatProperties;

    @Autowired
    private UserMapper userMapper;

    /**
     * 微信登录
     *
     * @param code
     * @return
     */
    @Override
    @Transactional
    public Result<UserLoginVO> loginByWeChat(UserLoginDTO code) {
        if(code == null){
            return Result.error("没有授权...");
        }
        System.out.println(code);


        //1、拿到code，进行封装
        Map<String, String> paramMap = new HashMap<>();
        paramMap.put("appid",weChatProperties.getAppid());
        paramMap.put("secret",weChatProperties.getSecret());
        paramMap.put("js_code",code.getCode());
        paramMap.put("grant_type","authorization_code");



        //2、把请求地址、请求体进行封装，请求微信接口，得到相应体
        String body = HttpClientUtil.doGet("https://api.weixin.qq.com/sns/jscode2session", paramMap);



        //3、解析响应体(使用)，得到openid
        Map map = JSON.parseObject(body, Map.class);
        String openid = map.get("openid").toString();
        log.info("得到的opinId: {}" + openid);



        //4、查看是否是新增用户，如果是，就注册
        User user = userMapper.getByOpenid(openid);
        if(user == null){
            user = User.builder()
                    .openid(openid)
                    .createTime(LocalDateTime.now())
                    .build();
            userMapper.insert(user);
        }



        //5、封装返回，需要的id，openid，token
        String token = JwtUtil.getToken(user.getId());
        UserLoginVO vo=UserLoginVO.builder()
                .id(user.getId())
                .openid(openid)
                .token(token)
                .build();

        return Result.success(vo);

    }
}
